package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"week62/client/client"
	"week62/client/request"
	"week62/common/proto/user"
)

func Login(c *gin.Context) {
	var data request.Login
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "参数错误",
			"Data": nil,
		})
		return
	}

	login, err := client.Login(c, &user.LoginReq{
		Tel:      data.Tel,
		Password: data.Password,
		Code:     data.Code,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "登录失败或验证码错误",
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "登录成功",
		"Data": login,
	})
}

func SendSms(c *gin.Context) {
	var data request.SendSms
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "参数错误",
			"Data": nil,
		})
		return
	}

	sms, err := client.SendSms(c, &user.SendSmsReq{Tel: data.Tel})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "验证码发送成功",
		"Data": sms,
	})
}

func AddOrder(c *gin.Context) {
	userId := c.GetUint("userId")
	var data request.AddOrder
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "参数错误",
			"Data": nil,
		})
		return
	}
	order, err := client.AddOrder(c, &user.AddOrderReq{
		UserId:  int64(userId),
		GoodsId: int64(data.GoodsId),
		PayType: int64(data.PayType),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "成功",
		"Data": order,
	})
}

func SyncGoods(c *gin.Context) {
	syncGoods, err := client.SyncGoods(c, &user.SyncGoodsReq{})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "成功",
		"Data": syncGoods,
	})
}
